class CreateOrders < ActiveRecord::Migration[5.1]
  def change
    [:orders, :order_histories].each do |table_name|
      auto_id = table_name == :orders
      table_spec = [table_name]
      table_spec << {id: false} unless auto_id

      create_table(*table_spec) do |t|
        t.bigint :id, primary_key: true unless auto_id

        t.belongs_to :payer, comment: '付款人ID'
        t.belongs_to :payment_request, index: false, comment: '付款请求ID'
        t.string :payment_method, limit: 6, comment: '支付方式'
        t.string :payment_username, limit: 50, comment: '支付平台的账号'
        t.string :transaction_code, limit: 50, comment: '支付平台流水号'
        t.string :state, default: 'new', null: false, limit: 10, comment: '订单状态'
        t.datetime :url_generated_at, comment: '支付URL生成时间'
        t.datetime :completed_at, comment: '支付流程完成时间'
        t.string :order_num, null: false, limit: 11, comment: '订单号'
        t.string :credit_card_num, limit: 50, comment: '银行卡号'
        t.string :credit_card_holder, limit: 50, comment: '持卡人'
        t.string :bank, limit: 50, comment: '开户银行'

        t.timestamps

        t.index :order_num, unique: true
        t.index :payment_request_id, unique: table_name == :orders
      end
      add_foreign_key table_name, :payers
      add_foreign_key table_name, :payment_requests
    end
  end
end
